import base64,pickle
from django_redis import get_redis_connection

def merge_cart_cookie_to_redis(request,user,response):
    """合并购物车"""
    # 从cookie中读取购物车数据
    cookie_cart_str = request.COOKIES.get("carts")

    # 如果cookie中无购物车数据,终止逻辑
    if not cookie_cart_str:
        return response

    # 如果cookie中有购物车数据,转购物车字典
    cookie_cart_dict = pickle.loads(base64.b64decode(cookie_cart_str.encode()))

    # 准备新数据容器
    new_cart_dict = {}
    new_selected_sku_ids = []
    new_unselected_sku_ids = []

    # 遍历cookie中购物车字典,将要合并的数据添加到数据容器(重要)
    for sku_id,cookie_dict in cookie_cart_dict.items():
        # 构造新的购物车字典
        new_cart_dict[sku_id] = cookie_dict["count"]
        # 构造被勾选的商品的sku_id列表
        if cookie_dict["selected"]:
            new_selected_sku_ids.append(sku_id)
        else:
            # 未被勾选的
            new_unselected_sku_ids.append(sku_id)

    # 将数据容器中的购物车数据同步到redis数据库(重要)
    redis_conn = get_redis_connection("carts")
    pl = redis_conn.pipeline()
    # 同步到sku_id 和 count
    pl.hmset("carts_%s" % user.id,new_cart_dict)
    # 同步勾选状态
    if new_selected_sku_ids:
        pl.sadd("selected_%s" %user.id,*new_selected_sku_ids)
    # 同步未勾选状态
    if new_unselected_sku_ids:
        pl.srem("selected_%s" % user.id, *new_unselected_sku_ids)

    # 执行
    pl.execute()

    # 清空cookie中购物车数据
    response.delete_cookie("carts")

    # 将响应对象还出去

    return response



